package com.zxl.live.screen.screen.ui.widget.panel;

import android.content.Context;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.MotionEvent;

import com.zxl.live.screen.screen.constant.ScreenSetting;
import com.zxl.live.screen.screen.ui.widget.surface.BasePanel;
import com.zxl.live.screen.screen.utils.FlowerFactory;
import com.zxl.live.screen.screen.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.List;

public class ScreenPanel extends BasePanel {

    private static ScreenPanel sInstence;

    private Object mLock;

    private boolean mIsPort;

    private List<ScreenSpirit> mList;

    private FlowerFactory mFlowerFactory;

    private ScreenPanel(Context context) {
        mLock = new Object();
        mList = new ArrayList<>();
        mIsPort = ScreenUtils.isPort();
        mFlowerFactory = new FlowerFactory(this, context);
        init();
    }

    public static ScreenPanel getInstence(Context context) {
        if (null == sInstence) {
            sInstence = new ScreenPanel(context);
        }
        return sInstence;
    }

    private void init() {
        new Thread() {

            @Override
            public void run() {
                mFlowerFactory.createFlowers(ScreenSetting.sEffciencyType, ScreenSetting.sEffciencySize);
            }

        } .start();

    }

    public void reset() {
        init();
    }

    public void resetData(List<ScreenSpirit> tmp) {
        synchronized (mList) {
            mList.clear();
            mList.addAll(tmp);
        }
    }

    @Override
    public void doDraw(Camera camera, Matrix matrix, Canvas canvas, Paint paint) {
        if (!mList.isEmpty()) {
            if (mIsPort != ScreenUtils.isPort()) {
                mIsPort = ScreenUtils.isPort();
                synchronized (mLock) {
                    for (ScreenSpirit screenSpirit : mList) {
                        screenSpirit.reset();
                    }
                }
            }

            synchronized (mLock) {
                for (ScreenSpirit screenSpirit : mList) {
                    screenSpirit.doDraw(camera, matrix, canvas, paint);
                }
            }
        }
    }

    @Override
    public void logic() {
        if (!mList.isEmpty()) {
            synchronized (mLock) {
                for (ScreenSpirit screenSpirit : mList) {
                    screenSpirit.logic();
                }
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return false;
    }


}
